const WebSocket = require('ws');

class WebSocketUtils {
    static generateClientId() {
        return Math.random().toString(36).substr(2, 9);
    }

    static isConnectionOpen(ws) {
        return ws && ws.readyState === WebSocket.OPEN;
    }

    static sendMessage(ws, type, data = {}) {
        if (this.isConnectionOpen(ws)) {
            const message = {
                type,
                timestamp: new Date().toISOString(),
                ...data
            };
            ws.send(JSON.stringify(message));
            return true;
        }
        return false;
    }

    static sendError(ws, message, code = 'UNKNOWN_ERROR') {
        return this.sendMessage(ws, 'error', {
            code,
            message
        });
    }

    static sendSuccess(ws, data = {}) {
        return this.sendMessage(ws, 'success', data);
    }

    static validateMessage(data, requiredFields = []) {
        for (const field of requiredFields) {
            if (!data.hasOwnProperty(field)) {
                return {
                    valid: false,
                    error: `缺少必需字段: ${field}`
                };
            }
        }
        return { valid: true };
    }

    static logConnection(ws, action) {
        const clientInfo = {
            id: ws.id || 'unknown',
            type: ws.wsType || 'unknown',
            timestamp: new Date().toISOString(),
            action
        };
        console.log('WebSocket连接事件:', clientInfo);
    }

    static setupConnectionLogging(ws, wss) {
        ws.id = this.generateClientId();
        
        this.logConnection(ws, 'connected');
        
        ws.on('close', (code, reason) => {
            this.logConnection(ws, 'disconnected');
        });
        
        ws.on('error', (error) => {
            this.logConnection(ws, 'error');
            console.error('WebSocket错误:', error);
        });
    }
}

module.exports = WebSocketUtils;
